#include "stdafx.h"
#include "log/formattingchannel.hpp"
#include "log/logregistry.hpp"

namespace JHCPP
{
	namespace log
	{	
		CFormattingChannel::CFormattingChannel() : m_pFormatter(0), m_pChannel(0)
		{
		}

		CFormattingChannel::CFormattingChannel(CFormatter* pFormatter) : m_pFormatter(pFormatter), m_pChannel(0)
		{
			if (m_pFormatter) m_pFormatter->add();
		}

		CFormattingChannel::CFormattingChannel(CFormatter* pFormatter, CChannel* pChannel)
		: m_pFormatter(pFormatter), m_pChannel(pChannel)
		{
			if (m_pFormatter) m_pFormatter->add();
			if (m_pChannel)   m_pChannel->add();
		}

		CFormattingChannel::~CFormattingChannel()
		{
			if (m_pChannel)   m_pChannel->release();
			if (m_pFormatter) m_pFormatter->release();
		}

		void CFormattingChannel::setFormatter(CFormatter* pFormatter)
		{
			if (m_pFormatter) m_pFormatter->release();
			m_pFormatter = pFormatter;
			if (m_pFormatter) m_pFormatter->add();
		}

		CFormatter* CFormattingChannel::getFormatter() const
		{
			return m_pFormatter;
		}

		void CFormattingChannel::setChannel(CChannel* pChannel)
		{
			if (m_pChannel) m_pChannel->release();
			m_pChannel = pChannel;
			if (m_pChannel) m_pChannel->add();
		}

		CChannel* CFormattingChannel::getChannel() const
		{
			return m_pChannel;
		}

		void CFormattingChannel::log(const CMessage& msg)
		{
			if (m_pChannel)
			{
				if (m_pFormatter)
				{
					std::string text;
					m_pFormatter->format(msg, text);
					m_pChannel->log(CMessage(msg, text));
				}
				else
				{
					m_pChannel->log(msg);
				}
			}
		}

		void CFormattingChannel::setProperty(const std::string& name, const std::string& value)
		{
			if (name == "channel")
				setChannel(CLogRegistry::defaultRegistry().channelForName(value));
			else if (name == "formatter")
				setFormatter(CLogRegistry::defaultRegistry().formatterForName(value));
			else if (m_pChannel)
				m_pChannel->setProperty(name, value);
		}

		void CFormattingChannel::open()
		{
			if (m_pChannel)
				m_pChannel->open();
		}

		void CFormattingChannel::close()
		{
			if (m_pChannel)
				m_pChannel->close();
		}
	}//end of namespace log
}//end of namespace JHCPP
